package com.ltw.dreamer.common.network;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlPage;

@Component
public class WebPageReader {
	private static final Logger logger = Logger.getLogger(WebPageReader.class);
	public String read(String url) {
		if (url == null) throw new IllegalArgumentException("传入参数为空");
		StringBuffer content = new StringBuffer();
		
		try {
			URL pageUrl = new URL(url);
			URLConnection connection = pageUrl.openConnection();
			connection.setConnectTimeout(10 * 1000);
			connection.setReadTimeout(10 * 1000);
			BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			String line;
			while ((line = reader.readLine()) != null) {
				content.append(line);
				content.append("\r\n");
			}
			reader.close();
		} catch (MalformedURLException e) {
			logger.info("解析网络文件出现异常：" + e.getLocalizedMessage());
			return null;
		}catch (IOException e) {
			logger.info("解析网络文件出现异常：" + e.getLocalizedMessage());
			return null;
		}
		return content.toString();
	}
	
	public String read(String url, boolean loadJs) {
		if (loadJs) {
			try {
				WebClient webClient = new WebClient();
				HtmlPage page;
				page = webClient.getPage(url);
				String pageAsXml = page.asXml();
				webClient.close();
				return pageAsXml;
			} catch (Exception e) {
				logger.info("解析网页信息出错。" + e.getLocalizedMessage());
				return null;
			}
		}
		return read(url);
	}
}
